package edu.gatech.gro.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;

import android.util.Log;
import edu.gatech.gro.model.ObjectResponse;
import edu.gatech.gro.model.parser.JsonHandler;

public class CommonResponseHandler implements ResponseHandler<ObjectResponse> {

	private static final String TAG = "COMMON_RESPONSE_HANDLER";

	private final JsonHandler mJsonHandler;

	public CommonResponseHandler(JsonHandler jsonHandler) {
		this.mJsonHandler = jsonHandler;
	}

	@Override
	public ObjectResponse handleResponse(HttpResponse r) {
		StringBuilder result = new StringBuilder();
		try {
			// First, we retrieve the xml string from the server
			BufferedReader br = new BufferedReader(new InputStreamReader(r.getEntity().getContent()));
			String line;
			while ((line = br.readLine()) != null) {
				result.append(line);
			}
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		}

		mJsonHandler.parse(result.toString());
		return mJsonHandler.getResponse();
	}
}
